//
//  Tooles.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2024/12/17.
//

#import "Tooles.h"
#import "EquesBusiness/YKIPinfo.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <SystemConfiguration/CaptiveNetwork.h> 
@implementation Tooles
// 获取token
+ (NSString *)getuserToken
{
      YKIPinfo *info = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
      return [info.pwd hasPrefix:@"$"] ? [info.pwd substringFromIndex:1] : info.pwd;
}

+ (NSString*)getChinaWordAndJosn:(id)json
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
    return  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+ (UIImage *)imageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
+ (NSString *)urlEncodeValue:(NSString *)str
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, NULL, kCFStringEncodingUTF8));
    return result;
}

+ (NSDictionary *)jsonAnalysis:(id)message
{
    NSDictionary *results;
    NSString *strMsg = (NSString *)message;
    if (strMsg) {
        NSData *jsonData = [strMsg dataUsingEncoding:NSUTF8StringEncoding];
        results = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
        return results;
        // NSJSONReadingMutableContainers
    }else{
        return results;
    }
}

+ (BOOL)albumAccess{
    
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
        return NO;
    }else{
        return YES;
    }
}

+ (NSString *)dateToUnixTime:(NSDate *)dateA{//读取
    
     NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
     NSString *timestr = [dateFormatter stringFromDate:dateA];
     NSDate *newdate = [dateFormatter dateFromString:timestr]; //---- 将字符串按formatter转成nsdate
     long long time = ((long long)[newdate timeIntervalSince1970])*1000;
     return [NSString stringWithFormat:@"%lld",time];

}

+ (NSString *)get_token{
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"EquesToken"];
    NSLog(@"get_token -- %@",token);
    return token;
}

+ (NSString *)get_uid{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"];
    NSLog(@"get_uid -- %@",uid);
    return uid;
}


// 将返回的时间戳转为年月日形式，再转为时间戳的字符串
+ (NSString*)timeToStrTime:(NSString*)creatime
{
    NSString *strTime = [Tooles Date2StrC:creatime]; //将报警的创建时间改年月日 的形式
    long long time = [Tooles timeStr2timeTimeInterval:strTime]*1000;   //将年月日 date改为时间戳
    NSString  *timeStr = [NSString stringWithFormat:@"%lld",time];
    return timeStr;
}

//程序中使用的，提交日期格式,参数为格林威治时间（距离1970年的毫秒数）
+ (NSString *)Date2StrC:(NSString *)indateTime
{
     NSString *dateLoca = [NSString stringWithFormat:@"%@",indateTime];
     NSTimeInterval time=[dateLoca doubleValue]/1000;//（参数若为秒数，这里不用除以1000）
     NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
     NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
     NSString *timestr = [dateFormatter stringFromDate:detaildate];
    return timestr;
}

//将日期转为时间戳 //存储checked 时间戳
+ (long long)timeStr2timeTimeInterval:(NSString*)date
{
     NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
     NSDate *newdate = [dateFormatter dateFromString:date]; //---- 将字符串按formatter转成nsdate
     return [newdate timeIntervalSince1970];
}

+ (NSString*)Date2StrD:(NSString*)indateTime{
    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateLoca = [NSString stringWithFormat:@"%@",indateTime];
    NSTimeInterval time=[dateLoca doubleValue]/1000;//（参数若为秒数，这里不用除以1000）
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    NSString *timestr = [dateFormatter stringFromDate:detaildate];
    return timestr;
}

+ (BOOL)isValidateNick:(NSString *)nick
{
    NSString *regex = @"^[a-zA-Z0-9_абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ\u4e00-\u9fa5]+$";//只含有汉字、数字、字母、下划线，下划线位置不限
    //NSString *regex = @"[`~!@#$%^&*+=|':;'\\[\\]<>/？~！@#￥%……&*（）——+|{}【】‘；：”“’。，,、？]";devicesInfo.alarm_enable = 0
    NSPredicate *passPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [passPre evaluateWithObject:nick];
}

+ (UIImage*)createImageWithColor:(UIColor*)color{
    
    CGRect rect = CGRectMake(0.0f,0.0f,1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context=UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+ (void)iOSv8AlertControllershow:(NSString*) strTitle actionTile1:(NSString*) strTitle1 actionTitle2:(NSString*) strTitle2
               currentController:(UIViewController*) curview actionBlock:(void *) action{
    
    UIAlertController *showAlert = [UIAlertController alertControllerWithTitle:strTitle message:nil preferredStyle:UIAlertControllerStyleAlert];
    if (strTitle1) {
        [showAlert addAction:[UIAlertAction actionWithTitle:strTitle1 style:UIAlertActionStyleCancel handler:nil]];
    }
    [showAlert addAction:[UIAlertAction actionWithTitle:strTitle2 style:UIAlertActionStyleDefault handler:(__bridge void (^ _Nullable)(UIAlertAction * _Nonnull __strong))(action)]];
    [curview presentViewController:showAlert animated:YES completion:nil];
}


#pragma mark -private
+ (NSString*)fetchSSIDInfo {
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    NSLog(@"Supported interfaces: %@", ifs);
    NSDictionary *info = nil;
    NSString *ssid = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSLog(@"%@ => %@", ifnam, info);
        if (info && [info count]) {
            if ([info objectForKey:@"SSID"]) {
                ssid = [info objectForKey:@"SSID"];
            }
            break;
        }
    }
    return ssid;
}

+ (NSString *)networkingStatesFromStatebar {

       AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
       NSString *connectionKind;
        switch ([manager networkReachabilityStatus]) {
            case AFNetworkReachabilityStatusNotReachable:
                connectionKind = @"notReachable";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                connectionKind = @"wifi";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                connectionKind = @"3G";
                break;
            case AFNetworkReachabilityStatusUnknown:
                connectionKind = @"notReachable";
                break;
            default:
                break;
        }
    return connectionKind;
}


@end
